package oa.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oa.bean.TUser;
import oa.service.UserService;
import oa.util.DateUtil;
import oa.util.ShiroUtil;
import oa.util.StringUtil;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
public class LoginController {
	
	@Resource
	//@Reference(check=false)
	private UserService userService;
	@Resource
	private DefaultKaptcha captchaProducer;
	
    /**
     * 获取验证码 的 请求路径
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")  
    public void defaultKaptcha(HttpServletRequest request,HttpServletResponse response) throws Exception{  
            byte[] captchaChallengeAsJpeg = null;    
             ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();    
             try {    
             //生产验证码字符串并保存到session中  
             String createText = captchaProducer.createText();  
             request.getSession().setAttribute("verifyCode", createText);  
             //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中  
             BufferedImage challenge = captchaProducer.createImage(createText);  
             ImageIO.write(challenge, "jpg", jpegOutputStream);  
             } catch (IllegalArgumentException e) {    
                 response.sendError(HttpServletResponse.SC_NOT_FOUND);    
                 return;    
             }   

             //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组  
             captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
             response.setHeader("Cache-Control", "no-store");    
             response.setHeader("Pragma", "no-cache");    
             response.setDateHeader("Expires", 0);    
             response.setContentType("image/jpeg");    
             ServletOutputStream responseOutputStream = response.getOutputStream();    
             responseOutputStream.write(captchaChallengeAsJpeg);    
             responseOutputStream.flush();    
             responseOutputStream.close();    
    } 

	@RequestMapping("/adminlogin")
	public String adminlogin() {
		return "adminlogin";
	}

	@RequestMapping("/admindologin")
	public String admindologin(@RequestParam(required=true) String username, 
			@RequestParam(required=true) String password,
			@RequestParam(required=true) String verifyCode,
			@RequestParam(name="url",defaultValue="/xadmin/adminindex") String url, 
			HttpSession session, Model model) {
		String loginUrl = "adminlogin";
		String code = (String)session.getAttribute("verifyCode");
		if(!verifyCode.equals(code)) {
			model.addAttribute("error", "您输入的验证码错误");
			return loginUrl;			
		}
		TUser user = userService.login(username);
		if(user == null) {
			model.addAttribute("error", "您输入的用户名不存在");
			return loginUrl;
		}else if(!user.getUserpassword().equals(StringUtil.MD5(password))) {
			model.addAttribute("error", "您输入的密码错误");
			return loginUrl;			
		}
		// 更新登录信息
		userService.updateuserlogin(username, DateUtil.getDateTime());
		//登录成功
		session.setAttribute("user", user);
		return "redirect:" + url;
	}

	@RequestMapping("/shirodologin")
	public String shirodologin(@RequestParam(required=true) String username, 
			@RequestParam(required=true) String password,
			@RequestParam(required=true) String verifyCode,
            @RequestParam(required=true, defaultValue = "false") Boolean remeberMe,
			@RequestParam(name="url",defaultValue="/xadmin/adminindex") String url, 
			HttpSession session, Model model) {
		String loginUrl = "adminlogin";
		String code = (String)session.getAttribute("verifyCode");
		if(!verifyCode.equals(code)) {
			model.addAttribute("error", "您输入的验证码错误");
			return loginUrl;
		}
		//通过用户名和密码生成 token
	    UsernamePasswordToken token = new UsernamePasswordToken(username, StringUtil.MD5(password));
		token.setRememberMe(remeberMe);
		//主题相当于用户
        Subject subject = SecurityUtils.getSubject();
        try {
        	subject.login(token);
        } catch(IncorrectCredentialsException ice) {
        	ice.printStackTrace();
        	model.addAttribute("error", "您输入的密码错误");
        	return loginUrl;
        } catch(Exception e) {
        	e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return loginUrl;
        }
        //将登录的用户信息存储到 session
		// subject.getSession() 赞同于 session
		subject.getSession().setAttribute("user", ShiroUtil.getPrincipal());
        // 更新登录信息
        userService.updateuserlogin(username, DateUtil.getDateTime());
        return "redirect:" + url;
	}
}
